/*
 * @Author: Cxy
 * @Date: 2021-05-21 20:43:07
 * @LastEditors: Cxy
 * @LastEditTime: 2022-11-17 15:36:48
 * @FilePath: /daimler-transport-admind:/giteeBlog/blogServe/socket/chat.js
 */
const { find, insertOne } = require('../mongo/db')
const io = require('./server')
module.exports = chat = socket => {
  // 文字聊天
  socket.on('send_Message_Data', async (data, callback) => {
    const { send_Admin_Code, send_Login_Device, send_Nick_Name, send_Head_Portrait, receive_Admin_Code, chat_Content } = data
    const sending_Time = Date.now()
    const receive_Data = await find('users', { admin_Code: receive_Admin_Code })
    const { socket_Id, head_Portrait: receive_Head_Portrait, nick_Name: receive_Nick_Name, login_Device: receive_Login_Device } = receive_Data.data[0]
    const chat_Data = {
      send_Admin_Code, send_Login_Device, send_Nick_Name, send_Head_Portrait, receive_Admin_Code, chat_Content,
      sending_Time, receive_Head_Portrait, receive_Nick_Name, receive_Login_Device
    }
    callback(chat_Data)
    await insertOne('chat', chat_Data)
    io.to(socket_Id).emit('receive_Message_Data', chat_Data);
  })
  // 邀请视音频通话
  socket.on('call_Phone', async (sender, admin_Code) => {
    socket.join(sender.admin_Code)
    const { data: [data] } = await find('users', { admin_Code })
    io.to(data.socket_Id).emit('pick_Phone', sender);
  })
  // 媒体协商、ICE传值
  socket.on('info_Switch', async (room, info) => {
    const room_Data = io.sockets.adapter.rooms.get(room)
    if (!room_Data.has(socket.id)) socket.join(room)
    socket.to(room).emit('info_Switch', info);
  })
  // 挂断后踢出呼叫者离开房间
  socket.on('hangUp_Phone', async (room) => {
    socket.to(room).emit('hangUp_Phone');
    const room_Data = io.sockets.adapter.rooms.get(room)
    const socket_Io = io.sockets.sockets
    console.log(room_Data.size);
    if(room_Data.size === 1) {
      for (let socket_Id of room_Data.values()) {
        socket_Io.get(socket_Id).leave(room)
      }
    } else {
      socket.leave(room)
    }
  })
}